const Mock = require('mockjs');
import * as mUtils from './mUtils.js';
let students = [
    {
        key:'1',
        name:'胡歌',
        studentId:'100001',
        className:'1001',
        sex:'男'
    },
    {
        key:'2',
        name:'霍建华',
        studentId:'100002',
        className:'1002',
        sex:'男'
    },{
        key:'3',
        name:'刘亦菲',
        studentId:'100003',
        className:'1001',
        sex:'女'
    },
    {
        key:'4',
        name:'刘诗诗',
        studentId:'100004',
        className:'1001',
        sex:'女'
    },{
        key:'5',
        name:'唐嫣',
        studentId:'100005',
        className:'1001',
        sex:'女'
    },
    {
        key:'6',
        name:'杨幂',
        studentId:'100006',
        className:'1001',
        sex:'女'
    }
]

const getStudentList = (ops) => {
    console.log(ops);
    const {current,pageSize,name,studentId,className,sex} = mUtils.param2Obj(ops.url);
    let students2 = students.filter((student,index) => {
        return student.name.search(name)!=-1 && student.studentId.search(studentId)!=-1 && student.className.search(className)!=-1 && student.sex.search(sex)!=-1;
    })
    console.log("students2",students2);
    const pageList = students2.filter((student,index) => {
        console.log(index);
        return index < current * pageSize  &&  index >= pageSize * (current-1);
      })
    return {
        status:200,
        message:"查询成功",
        data:pageList,
        current:current,
        pageSize:pageSize,
        total:students2.length,
    }
}

const saveStudent = (ops) => {
    console.log(ops);
    const obj = JSON.parse(ops.body);
    obj.key = (parseInt(students[students.length-1].key) + 1)+"";
    console.log("saveStudent",obj);
    students = students.concat(obj);
    return {
        status:200,
        message:"添加成功"
    }
}

const removeStudent = (ops) => {
    const {key} = mUtils.param2Obj(ops.url);
    console.log("删除操作",key);
    students = students.filter(item =>item.key!= key);
    return {
        status:200,
        message:"删除成功"
    }
}

const getStudentByKey = (ops) => {
    const {key} = mUtils.param2Obj(ops.url);
    console.log("更加key查询操作",key);
    const student = students.filter(item=>item.key==key);
    console.log("student",student);
    return {
        status:200,
        message:"查询成功",
        data:student[0]
    }
}

const updateStudent = (ops) => {
    const obj = JSON.parse(ops.body);
    console.log("更新操作",obj);
    students = students.map(item => {
        return item.key == obj.key ? obj : item;
    })
    return {
        status:200,
        message:"更新成功"
    }
}

Mock.mock(new RegExp("/api/students/getStudentList"),"get",getStudentList);
Mock.mock("/api/students/saveStudent","post",saveStudent);
Mock.mock(new RegExp("/api/students/removeStudent"),"get",removeStudent);
Mock.mock(new RegExp("/api/students/getStudentByKey"),"get",getStudentByKey);
Mock.mock("/api/students/updateStudent","post",updateStudent)